package com.songlanyun.common.utils;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelModel;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ImportUtil {
    /**
     * 导入excel
     *
     * @param titleRows          标题行数
     * @param headRows           头行数
     * @param clazz              数据类型
     * @param verifyHandler      校验
     * @param multipartFile      文件
     * @param isVerifyFailReturn 错误是否返回
     * @return
     * @throws Exception
     */
    public static Map<String, Object> importExcel(Integer titleRows,
                                                  Integer headRows,
                                                  Class<? extends IExcelModel> clazz,
                                                  IExcelVerifyHandler<? extends IExcelModel> verifyHandler,
                                                  MultipartFile multipartFile,
                                                  boolean isVerifyFailReturn) throws Exception {

        Map<String, Object> map = new HashMap<>();
        ExcelImportResult<IExcelModel> result = null;

        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headRows);
        // 开启Excel校验
        params.setNeedVerify(true);
        params.setVerifyHandler(verifyHandler);
        result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                clazz, params);

        System.out.println("是否校验失败: " + result.isVerifyFail());

        List<String> failList = new ArrayList<>();


        if (result.isVerifyFail()) {
            for (IExcelModel o : result.getFailList()) {
                failList.add(o.getErrorMsg());
            }
            map.put("status", false);
            map.put("fail", failList);
            if (isVerifyFailReturn) {
                return map;
            }
        } else {
            map.put("status", true);
        }

        //验证后不重复，有效的数据
        List<IExcelModel> list = result.getList();//18721
        map.put("success", list);

        return map;
    }




}
